package com.open.capacity.finance.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.finance.dto.audit_model_10.AuditModelStep1;
import com.open.capacity.finance.dto.echart.AuditWarnDto;
import com.open.capacity.finance.dto.echart.CompanyWarnDetailDto;
import com.open.capacity.finance.entity.AuditModelWarn;
import com.open.capacity.finance.service.AuditModelWarnService;
import com.open.capacity.finance.util.FileUtil;
import com.open.capacity.finance.util.PdfAuditModelReport;
import com.open.capacity.finance.util.PdfWatermark;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模型告警人员范围配置
 *
 * @author
 * @email
 * @date 2023-02-16 16:06:50
 */

@Slf4j
@RestController
@RequestMapping("auditmodelwarns")
public class AuditModelWarnController {

    @Autowired
    private AuditModelWarnService auditModelWarnService;

    @Value("${file.uploadpath:/usr/local/files/upload}")
    private String fileuploadPath;

    /**
     * 查询单条记录
     */
    @RequestMapping("/findById")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:list')")
    public Result findById(Long id) {
        return Result.succeed(auditModelWarnService.findById(id));
    }


    /**
     * 代办
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:list')")
    public PageResult list(@RequestParam Map<String, Object> params) {
        PageResult pageResult = auditModelWarnService.pageMy(params);
        return pageResult;
    }

    /**
     * 全部
     */
    @RequestMapping("/list_all")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:list')")
    public PageResult list_all(@RequestParam Map<String, Object> params) {
        PageResult pageResult = auditModelWarnService.pageAll(params);
        return pageResult;
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    @LogAnnotation(module = "预警", name = "删除")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:delete')")
    public Result delete(String ids) {
        auditModelWarnService.delete(ids);
        return Result.succeed("删除成功");
    }

    /**
     * 已读
     */
    @RequestMapping("/updateReadFlag")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:read')")
    public Result updateReadFlag(Long id) {
        auditModelWarnService.read(id);
        return Result.succeed("成功");
    }

    /**
     * 下发
     */
    @RequestMapping("/send")
    @LogAnnotation(module = "预警", name = "下发")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:send')")
    public Result send(String ids, Integer status) {
        auditModelWarnService.send(ids, status);
        return Result.succeed("操作成功");
    }


    /**
     * 忽略
     */
    @RequestMapping("/ingore")
    @LogAnnotation(module = "预警", name = "忽略")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:ingore')")
    public Result ingore(Long id, Long days) {
        auditModelWarnService.ingore(id, days);
        return Result.succeed("忽略成功");
    }


    /**
     * 申辩
     */
    @RequestMapping("/remark")
    @LogAnnotation(module = "预警", name = "解释备注")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:remark')")
    public Result remark(Long id, String remark) {
        auditModelWarnService.remark(id, remark);
        return Result.succeed("备注成功");
    }

    /**
     * 首页指标统计
     */
    @RequestMapping("/count")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:list')")
    public Result count(@RequestParam Map<String, Object> params) {
        AuditWarnDto dto = auditModelWarnService.countWarn();
        return Result.succeed(dto);
    }

    /**
     * 预警统计
     */
    @RequestMapping("/stat")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:list')")
    public Result stat(@RequestParam Map<String, Object> params) {
        AuditWarnDto dto = auditModelWarnService.countWarn();
        return Result.succeed(dto.getCompanywarnDetail1());
    }

    /**
     * 按照单位统计预警
     */
    @RequestMapping("/groupByModelId")
    @PreAuthorize("hasAnyAuthority('audit_model_warn:auditmodelwarn:list')")
    public Result groupByModelId(@RequestParam Map<String, Object> params) {
        List<CompanyWarnDetailDto> companyWarnDetailDtos = auditModelWarnService.groupByModelId();
        return Result.succeed(companyWarnDetailDtos);
    }

    /**
     * 导出报告 (导出pdf)
     */
    @GetMapping("/exportPdf")
    @LogAnnotation(module = "预警", name = "导出报告")
    public void exportPdf(@RequestParam Map<String, Object> params, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String companyId = params.get("companyId").toString();
        String planId = params.get("planId").toString();
        if ("-1".equals(companyId)) {
            companyId = "";
        }
        String modelId = params.get("modelId").toString();
        String ids = params.containsKey("keyValue") ? params.get("keyValue").toString() : "";
        if (StringUtil.isNotEmpty(ids)) {
            params.put("ids", ids.split(","));
        }
        List<AuditModelWarn> result = new ArrayList<>();
        try {
            result = auditModelWarnService.findAll(params);
        } catch (Exception e) {
            log.error("/exportPdf:{}", e);
        }

        String exportFileName = "";
        Map<String, List<AuditModelWarn>> collect = new HashMap<>();
        if ((StringUtil.isEmpty(companyId) && StringUtil.isEmpty(modelId)) || (StringUtil.isNotEmpty(companyId) && StringUtil.isEmpty(modelId))) {
            collect = result.stream().collect(Collectors.groupingBy(t -> t.getCompanyName(), HashMap::new, Collectors.toList()));
        } else if (StringUtil.isEmpty(companyId) && StringUtil.isNotEmpty(modelId)) {
            collect = result.stream().collect(Collectors.groupingBy(t -> t.getModelName(), HashMap::new, Collectors.toList()));
        }
        List<String> fileList = new ArrayList<>();
        for (Map.Entry<String, List<AuditModelWarn>> entry : collect.entrySet()) {
            String companyName = entry.getKey().replaceAll(" ", "");
            String filePath = fileuploadPath + "/temp/pdf/" + companyName + "报告.pdf";
            exportFileName = filePath;
            Document document = new Document(PageSize.A4);// 建立一个Document对象
            try {
                File file = new File(filePath);
                if (file.exists())
                    file.delete();
                file.createNewFile();
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
                writer.setPageEvent(new PdfWatermark("禁止外泄"));// 水印
                //writer.setPageEvent(new PdfHeaderFooter());// 页眉/页脚
                document.open();
                document.addTitle("广州市人民检察院两级院预警报告");// 标题
                new PdfAuditModelReport().generatePDF(document, fileuploadPath, entry.getValue());
            } catch (Exception e) {
                log.error(e.toString());
            } finally {
                document.close();
            }
            fileList.add(filePath);
        }

        try {
            if (StringUtil.isEmpty(companyId) && StringUtil.isEmpty(modelId)) {
                exportFileName = fileuploadPath + "/temp/pdf/两级院报告.zip";
                FileUtil.compressedFileToZip(exportFileName, fileList);
            }
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, exportFileName.substring(exportFileName.lastIndexOf("/") + 1)));
            FileUtils.writeBytes(exportFileName, response.getOutputStream());
            if (false) {
                FileUtils.deleteFile(exportFileName);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }

    }
}
